<template>
  <div class="table-container">
    <div class="operation-bar">
      <el-button type="primary" @click="handleImport">导入Excel</el-button>
      <el-button type="success" @click="exportToExcel">导出Excel</el-button>
      <el-button type="warning" @click="printTable">打印表格</el-button>
      <input
        type="file"
        ref="fileInput"
        style="display: none"
        accept=".xlsx, .xls"
        @change="onFileChange"
      />
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      ref="dataTable"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      <el-table-column prop="address" label="地址" ></el-table-column>
      <el-table-column prop="date" label="日期" width="180"></el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination"
    ></el-pagination>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { exportTableToPdf, printTable } from '@/utils/print'

export default {
  name: 'TableImportExportPrint',
  data() {
    return {
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      mockData: [
        {
          id: 1,
          name: '张三',
          age: 25,
          address: '北京市朝阳区',
          date: '2023-01-15'
        },
        {
          id: 2,
          name: '李四',
          age: 30,
          address: '上海市浦东新区',
          date: '2023-02-20'
        },
        {
          id: 3,
          name: '王五',
          age: 28,
          address: '广州市天河区',
          date: '2023-03-10'
        },
        {
          id: 4,
          name: '赵六',
          age: 35,
          address: '深圳市南山区',
          date: '2023-04-05'
        },
        {
          id: 5,
          name: '钱七',
          age: 40,
          address: '杭州市西湖区',
          date: '2023-05-12'
        }
      ]
    }
  },
  created() {
    this.initTableData()
  },
  methods: {
    initTableData() {
      this.loading = true
      // 模拟API请求
      setTimeout(() => {
        // 生成更多测试数据
        const data = []
        for (let i = 0; i < 50; i++) {
          const baseData = this.mockData[i % this.mockData.length]
          data.push({
            id: i + 1,
            name: baseData.name + (i > 4 ? i : ''),
            age: baseData.age + (i % 5),
            address: baseData.address,
            date: baseData.date
          })
        }
        this.tableData = data
        this.total = data.length
        this.loading = false
      }, 500)
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleImport() {
      this.$refs.fileInput.click()
    },
    onFileChange(e) {
      this.loading = true
      const files = e.target.files
      if (files.length <= 0) {
        this.loading = false
        return
      }

      const file = files[0]
      const reader = new FileReader()

      reader.onload = (e) => {
        try {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const jsonData = XLSX.utils.sheet_to_json(worksheet)

          // 处理导入的数据
          this.tableData = jsonData.map((item, index) => {
            return {
              id: index + 1,
              name: item['姓名'] || '',
              age: item['年龄'] || '',
              address: item['地址'] || '',
              date: item['日期'] || ''
            }
          })
          this.total = this.tableData.length
          this.$message.success('导入成功')
        } catch (error) {
          console.error('导入失败:', error)
          this.$message.error('导入失败，请检查文件格式')
        } finally {
          this.loading = false
          // 重置文件输入，以便可以重新选择相同的文件
          this.$refs.fileInput.value = ''
        }
      }

      reader.readAsArrayBuffer(file)
    },
    exportToExcel() {
      this.loading = true
      try {
        // 准备导出数据
        const exportData = this.tableData.map(item => {
          return {
            'ID': item.id,
            '姓名': item.name,
            '年龄': item.age,
            '地址': item.address,
            '日期': item.date
          }
        })

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData)
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '表格数据')

        // 生成Excel文件并下载
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
        
        const fileName = `表格数据_${new Date().toLocaleDateString()}.xlsx`
        FileSaver.saveAs(blob, fileName)
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.loading = false
      }
    },
    printTable() {
      // 方法一：使用我们创建的工具函数
      printTable(this.$refs.dataTable, '表格数据')
      
      // 方法二：导出为PDF
      // exportTableToPdf(this.$refs.dataTable, '表格数据')
    }
  }
}
</script>

<style scoped>
.table-container {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

@media print {
  .operation-bar, .pagination {
    display: none;
  }
}
</style>
